package com.web.exiaodao.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.entity.MakeMoneyTable;
import com.web.exiaodao.business.entity.User;
import com.web.exiaodao.business.repository.MakeMoneyTableRepository;
import com.web.exiaodao.business.repository.UserRepository;
import com.web.exiaodao.business.service.UserService;
import com.web.exiaodao.remote.vo.UserVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("UserService")
@Transactional(readOnly = false)
public class UserServiceImpl extends BaseService<User> implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    MakeMoneyTableRepository makeMoneyTableRepository;

    /**
     * 查询单条User信息
     *
     * @return 返回单个User对象
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<User> findOne(Long modelId) throws BusinessException {
        User obj = new User();
        if (modelId != 0) {
            obj = userRepository.findByIdAndStatusNot(modelId, XaConstant.Status.delete);
        }
        XaResult<User> xr = new XaResult<User>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(obj);
        } else {
            throw new BusinessException(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    /**
     * 分页查询状态非status的User数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象User集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<User>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<User> page = userRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), User.class), pageable);
        XaResult<Page<User>> xr = new XaResult<Page<User>>();
        xr.setObject(page);
        return xr;
    }

    /**
     * 分页查询状态status的User数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象User集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<User>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<User> page = userRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), User.class), pageable);
        XaResult<Page<User>> xr = new XaResult<Page<User>>();
        xr.setObject(page);
        return xr;
    }

    /**
     * 保存User信息
     *
     * @param model
     * @return
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<User> saveOrUpdate(User model) throws BusinessException {
        User obj = null;
        if (XaUtil.isNotEmpty(model.getId())) {
            obj = userRepository.findOne(model.getId());
        } else {
            obj = new User();
        }
        obj.setUserName(model.getUserName());
        obj.setPassword(model.getPassword());
        obj.setMobile(model.getMobile());
        obj.setPhoto(model.getPhoto());
        obj.setMemo(model.getMemo());
        obj.setBirthday(model.getBirthday());
        obj.setPayPassword(model.getPayPassword());
        obj.setRecommendPhone(model.getRecommendPhone());
        obj.setAlipayAccount(model.getAlipayAccount());
        obj.setBalance(model.getBalance());
        obj.setVip(model.getVip());
        obj.setVipOrderNo(model.getVipOrderNo());
        obj.setEmail(model.getEmail());
        obj = userRepository.save(obj);
        XaResult<User> xr = new XaResult<User>();
        xr.setObject(obj);
        return xr;
    }

    /**
     * 修改User状态，可一次修改多条   3删除  -1锁定  1正常
     *
     * @param modelIds
     * @param status
     * @return 返回User对象
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<User> multiOperate(
            String modelIds, Integer status) throws BusinessException {
        XaResult<User> xr = new XaResult<User>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                User obj = userRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = userRepository.save(obj);
                } else {
                    throw new BusinessException(XaConstant.Message.object_not_find);
                }
            }
        }
        return xr;
    }

    @Override
    public XaResult<Page<UserVo>> findListNEStatusByFilterByPage(Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<User> page = userRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), User.class), pageable);

        //// TODO:dz 2017/1/2
        List<UserVo> userVos = new ArrayList<>();
        for (int j = 0; j < page.getContent().size(); j++) {
            User user = page.getContent().get(j);
            UserVo userVo = JSON.parseObject(JSON.toJSONString(user), UserVo.class);
            if (XaUtil.isNotEmpty(user)) {
                List<MakeMoneyTable> mobj = makeMoneyTableRepository.findByUserIdAndStatusNot(user.getId(), XaConstant.Status.delete);
                if (XaUtil.isNotEmpty(mobj)) {
                    Long money = makeMoneyTableRepository.calculate(user.getId());
                    if (XaUtil.isNotEmpty(money)) {
                        userVo.setBalanceCoin(Double.valueOf(money));
                    } else {
                        userVo.setBalanceCoin(0.0);
                    }
                }
            }
            userVos.add(userVo);
        }
        XaResult<Page<UserVo>> xr = new XaResult<>();
        MyPage<UserVo> myPage = new MyPage<>(page, userVos);
        xr.setObject(myPage);
        return xr;
    }
}
